package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.MaterialCategory;
import com.example.chamberlainserver.Service.MaterialCategoryService;
import com.example.chamberlainserver.Vo.MaterialCategoryDTO;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 物资分类控制器
 */
@RestController
@RequestMapping("/category")
public class MaterialCategoryController {

    @Autowired
    private MaterialCategoryService materialCategoryService;

    /**
     * 添加物资分类
     * @param category 物资分类信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<ApiResponse<Void>> addCategory(@RequestBody MaterialCategory category) {
        try {
            boolean success = materialCategoryService.addCategory(category);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("添加分类成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("添加分类失败"));
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(400, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加分类失败：" + e.getMessage()));
        }
    }

    /**
     * 更新物资分类
     * @param category 物资分类信息
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<ApiResponse<Void>> updateCategory(@RequestBody MaterialCategory category) {
        try {
            if (category.getId() == null) {
                return ResponseEntity.ok(ApiResponse.error(400, "分类ID不能为空"));
            }
            boolean success = materialCategoryService.updateCategory(category);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新分类成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新分类失败"));
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(400, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新分类失败：" + e.getMessage()));
        }
    }

    /**
     * 删除物资分类
     * @param id 分类ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteCategory(@PathVariable Integer id) {
        try {
            boolean success = materialCategoryService.deleteCategory(id);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除分类成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除分类失败"));
            }
        } catch (IllegalArgumentException e) {
            return ResponseEntity.ok(ApiResponse.error(400, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除分类失败：" + e.getMessage()));
        }
    }

    /**
     * 根据ID查询物资分类
     * @param id 分类ID
     * @return 分类信息
     */
    @GetMapping("/get/{id}")
    public ResponseEntity<ApiResponse<MaterialCategory>> getCategoryById(@PathVariable Integer id) {
        try {
            MaterialCategory category = materialCategoryService.getCategoryById(id);
            if (category != null) {
                return ResponseEntity.ok(ApiResponse.success("获取分类成功", category));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "分类不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取分类失败：" + e.getMessage()));
        }
    }

    /**
     * 查询所有物资分类
     * @return 分类列表
     */
    @GetMapping("/list")
    public ResponseEntity<ApiResponse<List<MaterialCategory>>> getAllCategories() {
        try {
            List<MaterialCategory> categories = materialCategoryService.getAllCategories();
            return ResponseEntity.ok(ApiResponse.success("获取分类列表成功", categories));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取分类列表失败：" + e.getMessage()));
        }
    }

    /**
     * 获取分类树结构
     * @return 分类树
     */
    @GetMapping("/tree")
    public ResponseEntity<ApiResponse<List<MaterialCategory>>> getCategoryTree() {
        try {
            List<MaterialCategory> categoryTree = materialCategoryService.getCategoryTree();
            return ResponseEntity.ok(ApiResponse.success("获取分类树成功", categoryTree));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取分类树失败：" + e.getMessage()));
        }
    }
    
    /**
     * 获取分类树结构（使用DTO格式，包含子分类列表）
     * @return 分类树
     */
    @GetMapping("/tree/dto")
    public ResponseEntity<ApiResponse<List<MaterialCategoryDTO>>> getCategoryTreeDTO() {
        try {
            // 获取所有分类
            List<MaterialCategory> allCategories = materialCategoryService.getAllCategories();
            
            // 转换为DTO列表
            List<MaterialCategoryDTO> categoryDTOs = MaterialCategoryDTO.convertToDTOList(allCategories);
            
            // 构建树形结构
            List<MaterialCategoryDTO> categoryTree = MaterialCategoryDTO.buildCategoryTree(categoryDTOs);
            
            return ResponseEntity.ok(ApiResponse.success("获取分类树成功", categoryTree));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取分类树失败：" + e.getMessage()));
        }
    }

    /**
     * 根据父ID查询子分类
     * @param parentId 父分类ID
     * @return 子分类列表
     */
    @GetMapping("/sub/{parentId}")
    public ResponseEntity<ApiResponse<List<MaterialCategory>>> getSubCategories(@PathVariable Integer parentId) {
        try {
            List<MaterialCategory> subCategories = materialCategoryService.getSubCategories(parentId);
            return ResponseEntity.ok(ApiResponse.success("获取子分类成功", subCategories));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取子分类失败：" + e.getMessage()));
        }
    }
}